package com.ashin.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import cn.zhouyafeng.itchat4j.api.MessageTools;
import com.ashin.config.DuanjuConfig;
import com.ashin.config.KeywordConfig;
import com.ashin.constant.ChatType;
import com.ashin.entity.bo.Auth;
import com.ashin.entity.bo.ChatBO;
import com.ashin.entity.enums.ErrorEnum;
import com.ashin.service.AuthService;
import com.ashin.service.InteractService;
import com.ashin.util.BotUtil;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 微信消息处理程序
 *
 * @author ashinnotfound
 * @date 2023/03/19
 */
@Service
@Slf4j
public class WechatMessageHandler implements IMsgHandlerFace {
    private final InteractService interactService;
    private final KeywordConfig keywordConfig;
    private final BotUtil botUtil;
    private final DuanjuConfig duanjuConfig;
    private final AuthService authService;

    public WechatMessageHandler(InteractService interactService, KeywordConfig keywordConfig, BotUtil botUtil, DuanjuConfig duanjuConfig, AuthService authService) {
        this.interactService = interactService;
        this.keywordConfig = keywordConfig;
        this.botUtil = botUtil;
        this.duanjuConfig = duanjuConfig;
        this.authService = authService;
    }

    @Override
    public String textMsgHandle(BaseMsg baseMsg) {
        try {
            String authCode = duanjuConfig.getAuthCode();
            Core instance = Core.getInstance();
            if (!authCode.substring(8).equals(getSecret(authCode.substring(0, 8)))) {
                return ErrorEnum.NOAUTH.getMessage();
            }
//        Auth auth = authService.queryIfAuth(baseMsg.getFromUserName());
//        if (auth == null) {
//            log.info("群聊或私聊未授权，{}", baseMsg.getFromUserName());
//            return null;
//        }
            if (baseMsg.getText().contains("重置会话")) {
                botUtil.resetPrompt(baseMsg.getFromUserName());
                return "重置会话成功";
            }
            //如果是在群聊
            if (baseMsg.isGroupMsg()){
                String text = baseMsg.getText();
                if(CollUtil.isNotEmpty(duanjuConfig.getCustomReply())) {
                    String customReply = duanjuConfig.getCustomReply().get(text);
                    if (StringUtils.isNotBlank(customReply)) {
                        return customReply;
                    }
                }
                // 搜短剧
                String dealDuanju = dealDuanju(baseMsg);
                if (!dealDuanju.equals("-1")) {
                    return dealDuanju;
                }
                //存在@机器人的消息就向ChatGPT提问
                if (text.contains("@"+ Core.getInstance().getNickName())){
                    //去除@再提问
                    String prompt = text.replace("@"+ instance.getNickName() + " ", "").trim();
                    return textResponse(baseMsg.getFromUserName(), prompt);
                }
            }else {
                //不是在群聊 则直接回复
//                return textResponse(baseMsg.getFromUserName(), baseMsg.getText());
                return null;
            }
            return null;
        } catch (Exception e) {
            log.info("消息处理异常，{}", e.getMessage());
            return null;
        }

    }

    private String textResponse(String userName, String content) {
        if (keywordConfig.getReset().equals(content)){
            botUtil.resetPrompt(userName);
            return "重置会话成功";
        }else {
            ChatBO chatBO = new ChatBO();
            chatBO.setPrompt(content);
            chatBO.setSessionId(userName);
            if (content.startsWith(keywordConfig.getImage())) {
                chatBO.setPrompt(content.replaceFirst(keywordConfig.getImage() + " ", ""));
                chatBO.setChatType(ChatType.IMAGE);
            } else if (content.startsWith(keywordConfig.getAudio())) {
                return "微信暂不支持语音回复";
            } else {
                chatBO.setPrompt(content);
                chatBO.setChatType(ChatType.TEXT);
            }
            return interactService.chat(chatBO).getStringResult();
        }
    }

    @Override
    public String picMsgHandle(BaseMsg baseMsg) {
        return null;
    }

    @Override
    public String voiceMsgHandle(BaseMsg baseMsg) {
        return null;
    }

    @Override
    public String viedoMsgHandle(BaseMsg baseMsg) {
        return null;
    }

    @Override
    public String nameCardMsgHandle(BaseMsg baseMsg) {
        return null;
    }

    @Override
    public void sysMsgHandle(BaseMsg baseMsg) {
    }

    @Override
    public String verifyAddFriendMsgHandle(BaseMsg baseMsg) {
        MessageTools.addFriend(baseMsg, true);
        return null;
    }

    @Override
    public String mediaMsgHandle(BaseMsg baseMsg) {
        return null;
    }

    // 直接根据channel计算
    public static String getSecret(String channel) {
        return SecureUtil.md5("gpt:" + channel + ":duanju");
    }

    private String dealDuanju(BaseMsg baseMsg) {
        String[] split = duanjuConfig.getCommand().split(",");
        for (String command : split) {
            if (baseMsg.getText().startsWith(command)){
                return interactService.duanjuChat(baseMsg, command);
            }
        }
        return "-1"; // 非查短剧

    }
}
